// 在header 展示服务价格的表 
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { getTokensBalanceByUuid } from '@/api/userService';
import demon from "@/assets/images/deamo.webp"//钻石图片
import { getDynamicFonts } from '@/utils/fontUtils';
import { useNavigate } from 'react-router-dom';

interface TokenBalanceProps {
  userData: any;
  isMobile?: boolean;
  className?: string;
}

const TokenBalance: React.FC<TokenBalanceProps> = ({ userData, isMobile = false, className = '' }) => {
  const { t, i18n } = useTranslation();
  const navigate = useNavigate();
  const dynamicFonts = getDynamicFonts(i18n);
  const [tokensBalance, setTokensBalance] = useState<string | null>(null);
  const [displayBalance, setDisplayBalance] = useState<string | null>(null);
  const [balanceLoading, setBalanceLoading] = useState(false);
  const [isAnimating, setIsAnimating] = useState(false);
  const [changeDirection, setChangeDirection] = useState<'increase' | 'decrease' | null>(null);
  const prevBalanceRef = useRef<number | null>(null);
  const animationFrameRef = useRef<number | null>(null);
  const [showDropdown, setShowDropdown] = useState(false);

  // 根据当前语言决定显示的单位名称和服务单位
  const tokenUnit = i18n.language === 'en' ? 'Tokens' : 'ジェム';
  
  // 根据当前语言决定每种服务的单位后缀
  const getServiceUnit = (serviceType: string) => {
    if (i18n.language === 'ja') {
      // 日文单位
      switch (serviceType) {
        case 'text': return '／回'; // 文本聊天单位：每次
        case 'voice': return '／発言'; // 语音聊天单位：每句话
        case 'image': return '／枚'; // 图片生成单位：每张
        default: return '';
      }
    } else if (i18n.language === 'zh') {
      // 中文单位
      switch (serviceType) {
        case 'text': return '/条'; // 文本聊天单位
        case 'voice': return '/句'; // 语音聊天单位
        case 'image': return '/张'; // 图片生成单位
        default: return '';
      }
    } else {
      // 英文单位（默认）
      switch (serviceType) {
        case 'text': return ''; // 文本聊天单位
        case 'voice': return ''; // 语音聊天单位
        case 'image': return ''; // 图片生成单位
        default: return '';
      }
    }
  };

  // 缓动函数 - 更自然的动画效果
  const easeOutCubic = (x: number): number => {
    return 1 - Math.pow(1 - x, 3);
  };

  // 平滑动画函数
  const animateValue = useCallback((start: number, end: number, duration: number = 800) => {
    if (start === end) {
      setDisplayBalance(end.toFixed(1));
      return;
    }

    // 设置变化方向
    setChangeDirection(end > start ? 'increase' : 'decrease');
    setIsAnimating(true);
    let startTimestamp: number | null = null;

    // 清除之前的动画帧
    if (animationFrameRef.current !== null) {
      cancelAnimationFrame(animationFrameRef.current);
    }

    // 动画步骤函数
    const step = (timestamp: number) => {
      if (!startTimestamp) startTimestamp = timestamp;
      const elapsed = timestamp - startTimestamp;
      const progress = Math.min(elapsed / duration, 1);
      const easedProgress = easeOutCubic(progress);
      const current = start + easedProgress * (end - start);
      setDisplayBalance(current.toFixed(1));

      if (progress < 1) {
        animationFrameRef.current = requestAnimationFrame(step);
      } else {
        setDisplayBalance(end.toFixed(1));
        // 动画结束后延迟清除动画状态，让用户有时间注意到变化
        setTimeout(() => {
          setIsAnimating(false);
          setChangeDirection(null);
        }, 300);
        animationFrameRef.current = null;
      }
    };

    animationFrameRef.current = requestAnimationFrame(step);
  }, []);

  // 获取余额的函数，可以被外部触发刷新
  const fetchBalance = useCallback(async () => {
    if (userData?.visitor_uuid) {
      setBalanceLoading(true);
      try {
        const res = await getTokensBalanceByUuid(userData.visitor_uuid);
        if (res.data?.success && res.data?.data?.tokens_balance !== undefined) {
          // 获取新余额
          const newBalance = parseFloat(res.data.data.tokens_balance);
          setTokensBalance(newBalance.toFixed(1));

          // 如果有之前的余额，执行动画过渡
          if (prevBalanceRef.current !== null && !isNaN(newBalance)) {
            // 只有当余额有实际变化时才执行动画
            if (Math.abs(prevBalanceRef.current - newBalance) > 0.01) {
              animateValue(prevBalanceRef.current, newBalance);
            } else {
              setDisplayBalance(newBalance.toFixed(1));
            }
          } else {
            // 首次加载，直接设置
            setDisplayBalance(newBalance.toFixed(1));
          }

          // 更新前值引用
          prevBalanceRef.current = newBalance;
        } else {
          setTokensBalance(null);
          setDisplayBalance(null);
        }
      } catch (e) {
        setTokensBalance(null);
        setDisplayBalance(null);
      } finally {
        setBalanceLoading(false);
      }
    } else {
      setTokensBalance(null);
      setDisplayBalance(null);
    }
  }, [userData?.visitor_uuid, animateValue]);

  // 组件挂载时获取余额
  useEffect(() => {
    if (userData?.visitor_uuid) {
      fetchBalance();
    }
  }, [userData?.visitor_uuid, fetchBalance]);

  // 监听余额刷新事件
  useEffect(() => {
    const handleRefresh = () => {
      console.log('🪙 收到刷新余额事件，正在更新余额...');
      fetchBalance();
    };

    window.addEventListener('refresh-token-balance', handleRefresh);

    return () => {
      window.removeEventListener('refresh-token-balance', handleRefresh);
      // 清理动画帧
      if (animationFrameRef.current !== null) {
        cancelAnimationFrame(animationFrameRef.current);
      }
    };
  }, [fetchBalance]);
  
  // 当userData中的tokens_balance变化时，更新显示
  useEffect(() => {
    if (userData?.tokens_balance !== undefined && userData?.tokens_balance !== null) {
      const newBalance = parseFloat(userData.tokens_balance);
      if (!isNaN(newBalance)) {
        console.log('检测到userData中的tokens_balance更新:', newBalance);
        
        // 如果有之前的余额，执行动画过渡
        if (prevBalanceRef.current !== null) {
          // 只有当余额有实际变化时才执行动画
          if (Math.abs(prevBalanceRef.current - newBalance) > 0.01) {
            animateValue(prevBalanceRef.current, newBalance);
          }
        } else {
          // 首次加载，直接设置
          setDisplayBalance(newBalance.toFixed(1));
        }
        
        // 更新前值引用和tokens值
        prevBalanceRef.current = newBalance;
        setTokensBalance(newBalance.toFixed(1));
      }
    }
  }, [userData?.tokens_balance, animateValue]);

  // 添加全局样式到index.css中
  useEffect(() => {
    // 检查是否已经添加了这个样式
    const styleId = 'token-balance-animation-style';
    if (!document.getElementById(styleId)) {
      const style = document.createElement('style');
      style.id = styleId;
      style.textContent = `
        @keyframes fadeInOut {
          0% { opacity: 0; transform: translateY(-5px); }
          20% { opacity: 1; transform: translateY(0); }
          80% { opacity: 1; }
          100% { opacity: 0; }
        }
        
        @keyframes fadeIn {
          from { opacity: 0; transform: translateY(-10px); }
          to { opacity: 1; transform: translateY(0); }
        }
        
        .token-dropdown {
          animation: fadeIn 0.2s ease-out forwards;
        }
      `;
      document.head.appendChild(style);
    }

    return () => {
      // 清理样式
      const styleElement = document.getElementById(styleId);
      if (styleElement) {
        document.head.removeChild(styleElement);
      }
    };
  }, []);

  // 如果没有用户数据，不显示组件
  if (!userData?.visitor_uuid) {
    return null;
  }

  // 获取变化指示器样式
  const getChangeIndicator = () => {
    if (!isAnimating || !changeDirection) return null;

    return (
      <span
        className={`absolute -right-1 -top-1 text-xs ${changeDirection === 'increase' ? 'text-green-400' : 'text-red-400'
          }`}
        style={{
          animation: 'fadeInOut 1.2s ease-in-out',
          fontSize: '0.6rem'
        }}
      >
        {changeDirection === 'increase' ? '↑' : '↓'}
      </span>
    );
  };

  // 处理点击余额区域
  const handleBalanceClick = () => {
    navigate('/buygems');
  };

  return (
    <div
      className="relative"
      onMouseEnter={() => setShowDropdown(true)}
      onMouseLeave={() => setShowDropdown(false)}
    >
      <div
        className={`flex items-center text-white font-semibold bg-gray-800 rounded relative ${isMobile ? 'ml-2 px-2 py-0.5' : 'ml-4 px-3 py-1'
          } ${className} cursor-pointer hover:bg-gray-700 transition-colors`}
        style={{
          fontSize: isMobile ? (window.innerWidth <= 320 ? '0.65rem' : '0.75rem') : '0.875rem',
        }}
        onClick={handleBalanceClick}
      >
        {getChangeIndicator()}

        <img src={demon} alt="demon" className='w-5 h-5 mr-2 object-contain' />

        <span
          className={`truncate token-balance-value ${isAnimating
            ? (changeDirection === 'increase' ? 'text-green-400' : 'text-red-400')
            : ''
            }`}
          style={{
            maxWidth: isMobile ? (window.innerWidth <= 320 ? '40px' : '60px') : '80px',
            transition: 'color 0.3s ease, transform 0.3s ease',
            transform: isAnimating ? 'scale(1.05)' : 'scale(1)',
            fontFamily: dynamicFonts.font4
          }}
          data-balance={displayBalance}
        >
          {balanceLoading ? t('common.loading') : (displayBalance !== null ? displayBalance : '--')}
        </span>
      </div>

      {/* 下拉框列表 */}
      {showDropdown && (
        <div
          className="absolute right-0 mt-1 bg-[rgb(26,26,26)] rounded-lg shadow-lg border border-[rgb(54,54,54)] z-50 token-dropdown"
          style={{ minWidth: '13rem' }}
        >
          <div className="p-3 text-[0.75rem]" style={{ fontFamily: dynamicFonts.font4 }}>
            {/* 文本服务 */}
            <div className=" text-gray-400 mb-2">
              <span className='text-[rgb(252,118,138)]'>{t('tokenModal.TokenBalance.text')}: </span> 
              <span className=" text-white">{userData?.vip_live ? '0' : '0.1'} {tokenUnit}{getServiceUnit('text')}</span>
            </div>
            {/* 声音服务 */}
            <div className=" text-gray-400 mb-2">
              <span className='text-[rgb(252,118,138)]'>{t('tokenModal.TokenBalance.voice')}: </span>  
              <span className=" text-white">{userData?.vip_live ? '4' : '6'} {tokenUnit}{getServiceUnit('voice')}</span>
            </div>
            {/* 语音服务 */}
            <div className=" text-gray-400 mb-2">
              <span className='text-[rgb(252,118,138)]'>{t('tokenModal.TokenBalance.image')}: </span>  
              <span className=" text-white">{userData?.vip_live ? '8' : '10'} {tokenUnit}{getServiceUnit('image')}</span>
            </div>

          </div>
        </div>
      )}
    </div>
  );
};

// 为了支持全局更新余额的功能，创建一个事件总线
export const refreshTokenBalance = (forceValue?: number) => {
  // 触发自定义事件
  console.log('🪙 触发刷新余额事件', forceValue ? `强制值: ${forceValue}` : '');
  
  // 如果提供了强制值，直接更新localStorage中的余额
  if (forceValue !== undefined) {
    try {
      const userDataStr = localStorage.getItem('userData');
      if (userDataStr) {
        const userData = JSON.parse(userDataStr);
        userData.tokens_balance = forceValue;
        localStorage.setItem('userData', JSON.stringify(userData));
      }
    } catch (e) {
      console.error('强制更新余额失败:', e);
    }
  }
  
  // 触发事件以通知组件刷新
  window.dispatchEvent(new CustomEvent('refresh-token-balance'));
  
  // 额外的DOM更新以确保UI立即响应
  setTimeout(() => {
    try {
      const tokenElements = document.querySelectorAll('.token-balance-value');
      if (forceValue !== undefined && tokenElements.length > 0) {
        tokenElements.forEach(el => {
          if (el instanceof HTMLElement) {
            el.innerText = forceValue.toString();
            // 添加闪烁效果
            el.classList.add('text-green-400');
            setTimeout(() => el.classList.remove('text-green-400'), 1500);
          }
        });
      }
    } catch (e) {
      console.error('直接DOM更新余额失败:', e);
    }
  }, 50);
};

export default TokenBalance; 